using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace CKY.AgentPlatform.ModelConfigs
{
    /// <summary>
    /// 模型调用适配器接口
    /// </summary>
    public interface IModelInvocationAdapter
    {
        /// <summary>
        /// 支持的API模式
        /// </summary>
        ModelApiMode SupportedMode { get; }

        /// <summary>
        /// 支持的模型提供商
        /// </summary>
        ModelProvider SupportedProvider { get; }

        /// <summary>
        /// 适配器名称
        /// </summary>
        string Name { get; }

        /// <summary>
        /// 适配器版本
        /// </summary>
        string Version { get; }

        /// <summary>
        /// 是否支持流式输出
        /// </summary>
        bool SupportsStreaming { get; }

        /// <summary>
        /// 是否支持工具调用
        /// </summary>
        bool SupportsToolCalling { get; }

        /// <summary>
        /// 执行模型调用
        /// </summary>
        /// <param name="config">调用配置</param>
        /// <param name="request">调用请求</param>
        /// <param name="executionId">执行ID</param>
        /// <returns>调用结果</returns>
        Task<ModelInvocationResponse> InvokeAsync(
            ModelInvocationConfig config,
            ModelInvocationRequest request,
            string executionId);

        /// <summary>
        /// 验证配置是否有效
        /// </summary>
        /// <param name="config">调用配置</param>
        /// <returns>是否有效</returns>
        bool ValidateConfig(ModelInvocationConfig config);

        /// <summary>
        /// 获取适配器功能描述
        /// </summary>
        /// <returns>功能描述</returns>
        AdapterCapabilities GetCapabilities();

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="config">调用配置</param>
        /// <returns>测试结果</returns>
        Task<ConnectionTestResult> TestConnectionAsync(ModelInvocationConfig config);
    }

    /// <summary>
    /// 适配器功能描述
    /// </summary>
    public class AdapterCapabilities
    {
        /// <summary>
        /// 功能描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 支持的模型列表
        /// </summary>
        public List<string> SupportedModels { get; set; } = new List<string>();

        /// <summary>
        /// 最大输入长度
        /// </summary>
        public int MaxInputLength { get; set; }

        /// <summary>
        /// 最大输出长度
        /// </summary>
        public int MaxOutputLength { get; set; }

        /// <summary>
        /// 支持的参数列表
        /// </summary>
        public List<string> SupportedParameters { get; set; } = new List<string>();

        /// <summary>
        /// 特殊要求
        /// </summary>
        public Dictionary<string, string> SpecialRequirements { get; set; } = new Dictionary<string, string>();
    }

    /// <summary>
    /// 连接测试结果
    /// </summary>
    public class ConnectionTestResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 响应时间（毫秒）
        /// </summary>
        public long ResponseTimeMs { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// 测试详情
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new Dictionary<string, object>();
    }

    /// <summary>
    /// OpenAI兼容适配器
    /// </summary>
    public class OpenAICompatibleAdapter : IModelInvocationAdapter
    {
        public ModelApiMode SupportedMode => ModelApiMode.OpenAICompatible;
        public ModelProvider SupportedProvider => ModelProvider.Custom; // 可以被多个提供商使用
        public string Name => "OpenAI Compatible Adapter";
        public string Version => "1.0.0";
        public bool SupportsStreaming => true;
        public bool SupportsToolCalling => true;

        public async Task<ModelInvocationResponse> InvokeAsync(
            ModelInvocationConfig config,
            ModelInvocationRequest request,
            string executionId)
        {
            try
            {
                var startTime = DateTime.UtcNow;

                // 构建OpenAI兼容的请求体
                var openAIRequest = BuildOpenAIRequest(request);

                // 发送HTTP请求
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {config.ModelSpecificParams["ApiKey"]}");

                var response = await httpClient.PostAsJsonAsync(config.OpenAICompatibleEndpoint, openAIRequest);
                var responseContent = await response.Content.ReadAsStringAsync();

                // 解析响应
                var result = ParseOpenAIResponse(responseContent);
                result.ResponseTimeMs = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
                result.UsedApiMode = ModelApiMode.OpenAICompatible;

                return result;
            }
            catch (Exception ex)
            {
                return new ModelInvocationResponse
                {
                    Error = new ErrorResponse
                    {
                        Code = "ADAPTER_ERROR",
                        Message = $"OpenAI兼容适配器调用失败: {ex.Message}",
                        Type = "AdapterError",
                        InnerException = ex
                    },
                    UsedApiMode = ModelApiMode.OpenAICompatible
                };
            }
        }

        public bool ValidateConfig(ModelInvocationConfig config)
        {
            return !string.IsNullOrWhiteSpace(config.OpenAICompatibleEndpoint) &&
                   config.ModelSpecificParams.ContainsKey("ApiKey");
        }

        public AdapterCapabilities GetCapabilities()
        {
            return new AdapterCapabilities
            {
                Description = "OpenAI兼容模式的适配器，支持标准的OpenAI API格式",
                SupportedModels = new List<string> { "gpt-3.5-turbo", "gpt-4", "gpt-4-turbo", "gpt-4o" },
                MaxInputLength = 128000,
                MaxOutputLength = 4096,
                SupportedParameters = new List<string> { "temperature", "max_tokens", "top_p", "frequency_penalty", "presence_penalty", "stop" },
                SpecialRequirements = new Dictionary<string, string>
                {
                    { "format", "请求格式必须符合OpenAI API规范" },
                    { "auth", "使用Bearer Token进行认证" }
                }
            };
        }

        public async Task<ConnectionTestResult> TestConnectionAsync(ModelInvocationConfig config)
        {
            try
            {
                var startTime = DateTime.UtcNow;

                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {config.ModelSpecificParams["ApiKey"]}");

                // 发送测试请求
                var testRequest = new
                {
                    model = "gpt-3.5-turbo",
                    messages = new[] { new { role = "user", content = "Hello" } },
                    max_tokens = 5
                };

                var response = await httpClient.PostAsJsonAsync(config.OpenAICompatibleEndpoint, testRequest);
                var responseTime = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;

                return new ConnectionTestResult
                {
                    Success = response.IsSuccessStatusCode,
                    ResponseTimeMs = responseTime,
                    Details = new Dictionary<string, object>
                    {
                        { "statusCode", response.StatusCode },
                        { "endpoint", config.OpenAICompatibleEndpoint }
                    }
                };
            }
            catch (Exception ex)
            {
                return new ConnectionTestResult
                {
                    Success = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        private object BuildOpenAIRequest(ModelInvocationRequest request)
        {
            return new
            {
                model = request.Model,
                messages = request.Messages.Select(m => new
                {
                    role = m.Role,
                    content = m.Content
                }).ToList(),
                max_tokens = request.MaxTokens,
                temperature = request.Temperature,
                top_p = request.TopP,
                stream = request.Stream,
                stop = request.Stop,
                frequency_penalty = request.FrequencyPenalty,
                presence_penalty = request.PresencePenalty,
                tools = request.Tools?.Select(t => new
                {
                    type = t.Type,
                    function = new
                    {
                        name = t.Function.Name,
                        description = t.Function.Description,
                        parameters = t.Function.Parameters
                    }
                }).ToList()
            };
        }

        private ModelInvocationResponse ParseOpenAIResponse(string responseContent)
        {
            try
            {
                using var jsonDoc = System.Text.Json.JsonDocument.Parse(responseContent);
                var root = jsonDoc.RootElement;

                var response = new ModelInvocationResponse();

                if (root.TryGetProperty("id", out var idProp))
                    response.Id = idProp.GetString();

                if (root.TryGetProperty("object", out var objectProp))
                    response.Object = objectProp.GetString();

                if (root.TryGetProperty("created", out var createdProp))
                    response.Created = DateTime.UnixEpoch.AddSeconds(createdProp.GetInt64());

                if (root.TryGetProperty("model", out var modelProp))
                    response.Model = modelProp.GetString();

                // 解析响应内容
                if (root.TryGetProperty("choices", out var choicesProp) && choicesProp.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    var firstChoice = choicesProp.EnumerateArray().FirstOrDefault();
                    if (firstChoice.ValueKind != System.Text.Json.JsonValueKind.Undefined)
                    {
                        if (firstChoice.TryGetProperty("message", out var messageProp))
                        {
                            var responseMessage = new ResponseMessage();

                            if (messageProp.TryGetProperty("role", out var roleProp))
                                responseMessage.Role = roleProp.GetString();

                            if (messageProp.TryGetProperty("content", out var contentProp))
                                responseMessage.Content = contentProp.GetString();

                            response.Response = responseMessage;
                        }
                    }
                }

                // 解析使用统计
                if (root.TryGetProperty("usage", out var usageProp))
                {
                    response.Usage = new UsageInfo();

                    if (usageProp.TryGetProperty("prompt_tokens", out var promptTokensProp))
                        response.Usage.PromptTokens = promptTokensProp.GetInt32();

                    if (usageProp.TryGetProperty("completion_tokens", out var completionTokensProp))
                        response.Usage.CompletionTokens = completionTokensProp.GetInt32();

                    if (usageProp.TryGetProperty("total_tokens", out var totalTokensProp))
                        response.Usage.TotalTokens = totalTokensProp.GetInt32();
                }

                return response;
            }
            catch (Exception ex)
            {
                return new ModelInvocationResponse
                {
                    Error = new ErrorResponse
                    {
                        Code = "PARSE_ERROR",
                        Message = $"解析OpenAI响应失败: {ex.Message}",
                        Type = "ParseError",
                        InnerException = ex
                    }
                };
            }
        }
    }

    /// <summary>
    /// 智谱AI原生适配器
    /// </summary>
    public class ZhipuNativeAdapter : IModelInvocationAdapter
    {
        public ModelApiMode SupportedMode => ModelApiMode.Native;
        public ModelProvider SupportedProvider => ModelProvider.ZhipuAI;
        public string Name => "Zhipu AI Native Adapter";
        public string Version => "1.0.0";
        public bool SupportsStreaming => true;
        public bool SupportsToolCalling => true;

        public async Task<ModelInvocationResponse> InvokeAsync(
            ModelInvocationConfig config,
            ModelInvocationRequest request,
            string executionId)
        {
            try
            {
                var startTime = DateTime.UtcNow;

                // 构建智谱AI原生请求体
                var zhipuRequest = BuildZhipuRequest(request);

                // 发送HTTP请求
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {config.ModelSpecificParams["ApiKey"]}");

                var response = await httpClient.PostAsJsonAsync(config.NativeApiEndpoint, zhipuRequest);
                var responseContent = await response.Content.ReadAsStringAsync();

                // 解析响应
                var result = ParseZhipuResponse(responseContent);
                result.ResponseTimeMs = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
                result.UsedApiMode = ModelApiMode.Native;

                return result;
            }
            catch (Exception ex)
            {
                return new ModelInvocationResponse
                {
                    Error = new ErrorResponse
                    {
                        Code = "ADAPTER_ERROR",
                        Message = $"智谱AI原生适配器调用失败: {ex.Message}",
                        Type = "AdapterError",
                        InnerException = ex
                    },
                    UsedApiMode = ModelApiMode.Native
                };
            }
        }

        public bool ValidateConfig(ModelInvocationConfig config)
        {
            return !string.IsNullOrWhiteSpace(config.NativeApiEndpoint) &&
                   config.ModelSpecificParams.ContainsKey("ApiKey");
        }

        public AdapterCapabilities GetCapabilities()
        {
            return new AdapterCapabilities
            {
                Description = "智谱AI原生模式的适配器，支持GLM系列模型",
                SupportedModels = new List<string> { "glm-4", "glm-4-air", "glm-4-airx", "glm-4-flash", "glm-3-turbo" },
                MaxInputLength = 128000,
                MaxOutputLength = 4096,
                SupportedParameters = new List<string> { "temperature", "max_tokens", "top_p", "do_sample" },
                SpecialRequirements = new Dictionary<string, string>
                {
                    { "format", "请求格式必须符合智谱AI API规范" },
                    { "auth", "使用Bearer Token进行认证" }
                }
            };
        }

        public async Task<ConnectionTestResult> TestConnectionAsync(ModelInvocationConfig config)
        {
            try
            {
                var startTime = DateTime.UtcNow;

                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {config.ModelSpecificParams["ApiKey"]}");

                // 发送测试请求
                var testRequest = new
                {
                    model = "glm-4-flash",
                    messages = new[] { new { role = "user", content = "Hello" } },
                    max_tokens = 5
                };

                var response = await httpClient.PostAsJsonAsync(config.NativeApiEndpoint, testRequest);
                var responseTime = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;

                return new ConnectionTestResult
                {
                    Success = response.IsSuccessStatusCode,
                    ResponseTimeMs = responseTime,
                    Details = new Dictionary<string, object>
                    {
                        { "statusCode", response.StatusCode },
                        { "endpoint", config.NativeApiEndpoint }
                    }
                };
            }
            catch (Exception ex)
            {
                return new ConnectionTestResult
                {
                    Success = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        private object BuildZhipuRequest(ModelInvocationRequest request)
        {
            return new
            {
                model = request.Model,
                messages = request.Messages.Select(m => new
                {
                    role = m.Role,
                    content = m.Content
                }).ToList(),
                max_tokens = request.MaxTokens,
                temperature = request.Temperature,
                top_p = request.TopP,
                stream = request.Stream,
                // 智谱AI特有参数
                do_sample = true,
                presence_penalty = request.PresencePenalty,
                frequency_penalty = request.FrequencyPenalty
            };
        }

        private ModelInvocationResponse ParseZhipuResponse(string responseContent)
        {
            try
            {
                using var jsonDoc = System.Text.Json.JsonDocument.Parse(responseContent);
                var root = jsonDoc.RootElement;

                var response = new ModelInvocationResponse();

                if (root.TryGetProperty("id", out var idProp))
                    response.Id = idProp.GetString();

                if (root.TryGetProperty("object", out var objectProp))
                    response.Object = objectProp.GetString();

                if (root.TryGetProperty("created", out var createdProp))
                    response.Created = DateTime.UnixEpoch.AddSeconds(createdProp.GetInt64());

                if (root.TryGetProperty("model", out var modelProp))
                    response.Model = modelProp.GetString();

                // 解析响应内容
                if (root.TryGetProperty("choices", out var choicesProp) && choicesProp.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    var firstChoice = choicesProp.EnumerateArray().FirstOrDefault();
                    if (firstChoice.ValueKind != System.Text.Json.JsonValueKind.Undefined)
                    {
                        if (firstChoice.TryGetProperty("message", out var messageProp))
                        {
                            var responseMessage = new ResponseMessage();

                            if (messageProp.TryGetProperty("role", out var roleProp))
                                responseMessage.Role = roleProp.GetString();

                            if (messageProp.TryGetProperty("content", out var contentProp))
                                responseMessage.Content = contentProp.GetString();

                            response.Response = responseMessage;
                        }
                    }
                }

                // 解析使用统计
                if (root.TryGetProperty("usage", out var usageProp))
                {
                    response.Usage = new UsageInfo();

                    if (usageProp.TryGetProperty("prompt_tokens", out var promptTokensProp))
                        response.Usage.PromptTokens = promptTokensProp.GetInt32();

                    if (usageProp.TryGetProperty("completion_tokens", out var completionTokensProp))
                        response.Usage.CompletionTokens = completionTokensProp.GetInt32();

                    if (usageProp.TryGetProperty("total_tokens", out var totalTokensProp))
                        response.Usage.TotalTokens = totalTokensProp.GetInt32();
                }

                return response;
            }
            catch (Exception ex)
            {
                return new ModelInvocationResponse
                {
                    Error = new ErrorResponse
                    {
                        Code = "PARSE_ERROR",
                        Message = $"解析智谱AI响应失败: {ex.Message}",
                        Type = "ParseError",
                        InnerException = ex
                    }
                };
            }
        }
    }

    /// <summary>
    /// 聊天消息 - 保留向后兼容性
    /// </summary>
    public class ChatMessage : CKY.AgentPlatform.Common.Types.ChatMessage
    {
    }

    /// <summary>
    /// 工具调用 - 保留向后兼容性
    /// </summary>
    public class ToolCall : CKY.AgentPlatform.Common.Types.ToolCall
    {
    }
}